// \u4e00-\u9fa5] 中文验证规则
import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  data: {
    point:'',
    building:'',
    room:'',
    name:'',
    gender:1,
    mobile:'',
    idcardFrontUrl: '',
    idcardBackUrl: '',
  },
  rules:{
    name:[{ required: true, message: '请填写您的姓名!'},
    { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '业主姓名只能为中文!' }],
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请检查手机号码是否正确!' },
    ],
    idcardFrontUrl: [
      { required: true, message: '请上传身份证国徽面!' }
    ],
    idcardBackUrl: [
      { required: true, message: '请上传身份证照片面!' }
    ],
  },
  onLoad({point,building,room,id}){
    if(id) this.compileData(id)
    wx.setNavigationBarTitle({
      title: id?'编辑房屋':'添加房屋',
    })
    this.setData({point,building,room})
  },
  async submitForm() {
    //点击提交
   if(!this.validate()) return 
   // eslint-disable-next-line no-unused-vars
   const {__webviewId__,status,...data } = this.data
   console.log(data,'什么意思');
   const {code} = await wx.http.post('/room',data)
  //  console.log(code);
  if(code!==10000) return wx.utils.toast('上传失败')
  wx.navigateBack({
    delta: this.data.id?2:4,
  })
  },
  //编辑页面的处理函数
  async compileData(id){
    const {code,data} = await wx.http.get('/room/'+id)
    if(code!==10000) return wx.utils.toast()
    this.setData(data)
  },
  //单选框事件
  radioChange(ev) {
    this.setData({
      gender:ev.detail
    })
  },
  //点击上传图片
  async uploadPicture(ev){
    // console.log(ev);
    const type = ev.mark.type
    try {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType:['image'],
        sizeType:['compressed']
      })
      // console.log(res.tempFiles.tempFilePath);
    //开始上传文件
    wx.uploadFile({
      filePath: res.tempFiles[0].tempFilePath,
      name: 'file',
      url: wx.http.baseURL+'/upload',
      header:{Authorization: 'Bearer '+getApp().token},
      success:(res)=>{
        const data = JSON.parse(res.data)
        if(data.code!==10000) return wx.utils.toast('上传失败')
        this.setData({
          [type]:data.data.url
        })
      }

    })
    } catch (error) {
      console.log(error);
    }
    
  },
  
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark.type
    this.setData({ [type]: '' })
  },
})
